package com.example.wudi.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import com.example.wudi.entity.User;
import com.example.wudi.res.Res;
import com.example.wudi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("login")
    @CrossOrigin
    Res findAll(@RequestParam String userName, @RequestParam String passWord) {
        final User login = userService.login(userName, passWord);
        if(login != null) {
            StpUtil.login(login.getId());
            final SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            return Res.oktl("登录成功", login, tokenInfo.tokenValue);
        } else {
            return Res.nolit("账号或者密码错误", null);
        }
    }

    @SaCheckLogin
    @SaCheckPermission("user:select")
    @GetMapping("findAll")
    @CrossOrigin
    Res findAll() {
        final List<User> all = userService.findAll();
        if(all.size() > 0) {
            return Res.okLit("", all);
        } else {
            return Res.nolit("", all);
        }
    }

    @SaCheckLogin
    @SaCheckPermission("user:select")
    @GetMapping("findOne")
    @CrossOrigin
    Res findOne(@RequestParam int id) {
        final User userById = userService.findUserById(id);
        if(userById != null) {
            return Res.okLit("", userById);
        } else {
            return Res.nolit("", userById);
        }
    }

    @SaCheckLogin
    @SaCheckPermission("user:add")
    @PostMapping("add")
    @CrossOrigin
    Res add(@RequestBody User user) {
        final int i = userService.addUser(user);
        if(i > 0) {
            return Res.okLit("创建成功", i);
        } else {
            return Res.nolit("创建失败", i);
        }
    }

    @SaCheckLogin
    @SaCheckPermission("user:update")
    @PostMapping("update")
    @CrossOrigin
    Res update(@RequestBody User user) {
        final int i = userService.update(user);
        if(i > 0) {
            return Res.okLit("修改成功", i);
        } else {
            return Res.nolit("修改失败", i);
        }
    }


    @SaCheckLogin
    @SaCheckPermission("user:delete")
    @PostMapping("delete")
    @CrossOrigin
    Res delete(@RequestParam int id) {
        final int i = userService.delete(id);
        if(i > 0) {
            return Res.okLit("删除成功", i);
        } else {
            return Res.okLit("删除成功", i);
        }
    }

}
